Minimise allocations for ModifierSum#739
Conversation
2351277 to
99490eb
Compare
|
As a general note, calling reserve explicitly is typically only an optimization if you can find a one-time upper bound on the possible growth and thereby call reserve once instead of allowing the vector to grow naturally. However, if you call reserve repeatedly you run the risk of performing much worse than the vector's normal exponential growth. The growth factor of the vector is designed so that adding elements is amortized O(1). Repeated calls to reserve that grow the vector only by some amount that we can place an upper bound on (as presumably happens here, since the total number of possible modifiers is bounded) makes the entire process (cycles of reserve + element additions) amortized O(n). In your particular case, a little back of the napkin math will show that just allocating space for every country to have every possible modifier times the number of land provinces is within the memory budget, so you can use that as the value for a single reservation and be very, very unlikely to ever need to grow the vectors. |
CountryInstance::contribute_province_modifier_sumis called for each province (expect 10s-100s per country). Every call toModifierSum::add_modifier_sumcalledreserve_more, which is defined as:This resulted in repeated allocations, possibly reallocating the country's modifiersum for each controlled province.
Instead we now first sum the extra capacity for all provinces and then reserve once.